package com.song.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.common.base.UserContextInfo;
import com.song.common.enums.CollectTypeEnums;
import com.song.common.response.PageInfo;
import com.song.framework.async.AsyncFactory;
import com.song.framework.context.ContextUserInfoThreadHolder;
import com.song.framework.exception.ServiceException;
import com.song.module.admin.entity.ApCollect;
import com.song.module.admin.entity.ApCookbookIngredient;
import com.song.module.admin.entity.ApCookbookInstruction;
import com.song.module.admin.mapper.ApCollectMapper;
import com.song.module.admin.mapper.ApCookbookIngredientMapper;
import com.song.module.admin.mapper.ApCookbookInstructionMapper;
import com.song.module.admin.request.ApUserBrowseRequest;
import com.song.module.admin.response.ApCookbookResponse;
import com.song.module.admin.service.IApUserBrowseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.song.module.admin.request.ApCookbookRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.song.module.admin.mapper.ApCookbookMapper;
import org.springframework.beans.BeanUtils;
import com.song.module.admin.entity.ApCookbook;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.song.module.admin.service.IApCookbookService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 菜谱业务层处理
 *
 * @author song
 * @date 2024-02-24
 */
@Slf4j
@Service
@AllArgsConstructor
public class ApCookbookServiceImpl implements IApCookbookService {

    private final ApCookbookMapper baseMapper;

    private final ApCollectMapper apCollectMapper;

    private final ApCookbookIngredientMapper cookbookIngredientMapper;

    private final ApCookbookInstructionMapper cookbookInstructionMapper;

    private final IApUserBrowseService userBrowseService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApCookbook add(ApCookbookRequest request) {
        ApCookbook entity = ApCookbook.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ApCookbookRequest request) {
        ApCookbook entity = ApCookbook.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public ApCookbook getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<ApCookbook> list(ApCookbookRequest request) {
        LambdaQueryWrapper<ApCookbook> query = this.buildWrapper(request).orderByAsc(ApCookbook::getCollectNum);
        return baseMapper.selectList(query);
    }

    //    菜谱列表查询
    @Override
    public PageInfo<ApCookbook> pageList(ApCookbookRequest request) {
        Page<ApCookbook> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<ApCookbook> query = this.buildWrapper(request).orderByAsc(ApCookbook::getCollectNum);
        IPage<ApCookbook> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }

    //    菜谱详情信息
    @Override
    public ApCookbookResponse appDetail(String id) {
        ApCookbook apCookbook = baseMapper.selectOne(Wrappers.lambdaQuery(ApCookbook.class).eq(ApCookbook::getFoodId, id));
        if (Objects.isNull(apCookbook)) {
            throw new ServiceException("当前菜谱不存在");
        }
        UserContextInfo info = ContextUserInfoThreadHolder.get();
        boolean isCollect = false;
        if (Objects.nonNull(info)) {
            // 查询是否收藏
            ApCollect collect = apCollectMapper.selectOne(Wrappers.lambdaQuery(ApCollect.class).eq(ApCollect::getFoodId, id).eq(ApCollect::getUserId, info.getId()));
            if (Objects.nonNull(collect)) {isCollect = true;}}
        // 异步增加浏览记录
        AsyncFactory.runAsync(() -> userBrowseService.add(ApUserBrowseRequest.builder().userId(info.getId()).foodId(Long.valueOf(id)).build()));
        List<ApCookbookIngredient> ingredientList = cookbookIngredientMapper.selectList(Wrappers.lambdaQuery(ApCookbookIngredient.class).eq(ApCookbookIngredient::getFoodId, id));
        List<ApCookbookInstruction> instructionList = cookbookInstructionMapper.selectList(Wrappers.lambdaQuery(ApCookbookInstruction.class).eq(ApCookbookInstruction::getFoodId, id).orderByAsc(ApCookbookInstruction::getStep));
        return ApCookbookResponse.builder().apCookbook(apCookbook).cookbookIngredientList(ingredientList).cookbookInstructionList(instructionList).collect(isCollect).build();
    }

    @Override
    public void updateCollectNum(Integer type, String foodId) {
        ApCookbook apCookbook = baseMapper.selectOne(Wrappers.lambdaQuery(ApCookbook.class).eq(ApCookbook::getFoodId, foodId));
        if (Objects.isNull(apCookbook)) {
            return;
        }
        if (CollectTypeEnums.COLLECT.getType().equals(type)) {
            apCookbook.setCollectNum(apCookbook.getCollectNum() + 1);
        } else {
            if (apCookbook.getCollectNum() > 0) {
                apCookbook.setCollectNum(apCookbook.getCollectNum() - 1);
            }
        }
        baseMapper.updateById(apCookbook);
    }

    private LambdaQueryWrapper<ApCookbook> buildWrapper(ApCookbookRequest param) {
        LambdaQueryWrapper<ApCookbook> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getName())) {
            query.like(ApCookbook::getName, param.getName());
        }
        if (StringUtils.isNotBlank(param.getDescribe())) {
            query.like(ApCookbook::getDescription, param.getDescribe());
        }
        return query;
    }

}
